package com.sz.freemusic.net;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.Bitmap;

import com.sz.data.Artist;
import com.sz.freemusic.common.ApplicationData;
import com.sz.freemusic.net.listeners.ImageDownloadListener;

public class RequestQueue {
	ExecutorService requestsPool;
	ExecutorService imagePool;
	
	private static RequestQueue INSTANCE = null;
			
	public static RequestQueue getInstance() {
		synchronized (RequestQueue.class){
			if (INSTANCE == null) {
				INSTANCE = new RequestQueue();
			}
		}
		return INSTANCE;
	}
	
	private RequestQueue() {
		requestsPool = Executors.newSingleThreadExecutor();
		imagePool = Executors.newSingleThreadExecutor();
	}
	
	
	public void enqueueRequest(Runnable r) {
		requestsPool.execute(r);
	}
	
	public void enqueImageDownload(final Artist artist, final ImageDownloadListener imageDownloadListener) {
		imagePool.execute(new Runnable() {
			
			@Override
			public void run() {
				ApplicationData applicationData = ApplicationData.getInstance();
				Bitmap bmp = applicationData.getBitmapCache().getBmpFromCache(artist.getImageUrl());
				if (bmp == null) {
					bmp = HttpRetreiver.downloadBitmap(artist.getImageUrl());
					applicationData.getBitmapCache().addBmpToCache(artist.getImageUrl(), bmp);
				}
				if (bmp != null) {
//					artist.setArtistImage(bmp);
					if (imageDownloadListener != null) {
						imageDownloadListener.imageDone(artist);
					}
				}
				
				
			}
		});
	}
	
	
}
